package com.mproject.network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.util.Log;

import com.mproject.customclass.Category;
import com.mproject.customclass.Project;
import com.mproject.customclass.Student;

public class IVLE_API_Helper {
	private static String tag = "IVLE_API_Helper";
	public static String APIKey = "yng5a0cke29Bm09616n63";

	public static String getUserId(String token) throws Exception {
		String url = "https://ivle.nus.edu.sg/api/Lapi.svc/UserID_Get?APIKey="+APIKey+"&Token="+token;
		HttpClient client=new  DefaultHttpClient();
		HttpGet get=new HttpGet(url);

		//adding parameters to the post request


		//exexcuting the post request and getting the response
		HttpResponse resp=client.execute(get);

		BufferedReader br=new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
		StringBuffer sb = new StringBuffer("");
		String response_line = "";
		String NL = System.getProperty("line.separator");

		while((response_line=br.readLine())!=null)
		{
			sb.append(response_line+NL);
		}
		br.close();


		response_line=sb.toString();
		response_line = response_line.substring(1,response_line.lastIndexOf("\""));
		Log.e("IVLE_API_Helper", response_line);
		return response_line;
	}
	public static String getUserFullName(String token) throws Exception {
		String url = "https://ivle.nus.edu.sg/api/Lapi.svc/UserName_Get?APIKey="+APIKey+"&Token="+token;

		Log.e(tag, url);
		HttpClient client=new  DefaultHttpClient();
		HttpGet get=new HttpGet(url);

		//adding parameters to the post request


		//exexcuting the post request and getting the response
		HttpResponse resp=client.execute(get);

		BufferedReader br=new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
		StringBuffer sb = new StringBuffer("");
		String response_line = "";
		String NL = System.getProperty("line.separator");

		while((response_line=br.readLine())!=null)
		{
			sb.append(response_line+NL);
		}
		br.close();


		response_line=sb.toString();
		Log.e("IVLE_API_Helper", response_line);
		response_line = response_line.substring(1,response_line.lastIndexOf("\""));
		Log.e("IVLE_API_Helper", response_line);
		return response_line;
	}

	//login function
	public static String loginToIVLE(String username, String password) {

		StringBuffer stringBuffer = new StringBuffer("");
		BufferedReader bufferedReader = null;
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost request = new HttpPost("https://ivle.nus.edu.sg/api/login/?apikey="+APIKey);
		List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("__LASTFOCUS", ""));
		postParameters.add(new BasicNameValuePair("__EVENTTARGET", ""));
		postParameters.add(new BasicNameValuePair("__EVENTARGUMENT", ""));
		postParameters.add(new BasicNameValuePair("__VIEWSTATE", "/wEPDwULLTEzODMyMDQxNjEPZBYCAgEPZBYEAgEPD2QWAh4Gb25ibHVyBQ91c2VySWRUb1VwcGVyKClkAgkPD2QWBB4Lb25tb3VzZW92ZXIFNWRvY3VtZW50LmdldEVsZW1lbnRCeUlkKCdsb2dpbmltZzEnKS5zcmM9b2ZmaW1nLnNyYzE7Hgpvbm1vdXNlb3V0BTRkb2N1bWVudC5nZXRFbGVtZW50QnlJZCgnbG9naW5pbWcxJykuc3JjPW9uaW1nLnNyYzE7ZBgBBR5fX0NvbnRyb2xzUmVxdWlyZVBvc3RCYWNrS2V5X18WAQUJbG9naW5pbWcx"));
		postParameters.add(new BasicNameValuePair("__SCROLLPOSITIONX", "0"));
		postParameters.add(new BasicNameValuePair("__SCROLLPOSITIONY", "0"));
		postParameters.add(new BasicNameValuePair("userid", username.toUpperCase()));
		postParameters.add(new BasicNameValuePair("password", password));


		try {
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParameters);
			request.setEntity(entity);

			HttpResponse response= httpClient.execute(request);

			bufferedReader = new BufferedReader(
					new InputStreamReader(response.getEntity().getContent()));

			String line = "";
			String LineSeparator = System.getProperty("line.separator");
			while ((line = bufferedReader.readLine()) != null) {
				stringBuffer.append(line + LineSeparator);	
			}
			bufferedReader.close();			

		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();

		}finally{
			if (bufferedReader != null){
				try {
					bufferedReader.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		Log.e("tag",stringBuffer.toString());
		return stringBuffer.toString().substring(0, stringBuffer.toString().length()-1);

	}

	//get all projects of the current user
	public static List<Project> getAllProjects(String token) throws Exception{
		List<Project> projects = new ArrayList<Project>();

		String url = "https://ivle.nus.edu.sg/api/Lapi.svc/Communities?APIKey=" + APIKey + "&AuthToken=" + token + "&Duration=0";
		HttpClient client=new  DefaultHttpClient();
		HttpGet get=new HttpGet(url);
		HttpResponse resp=client.execute(get);

		BufferedReader br=new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
		StringBuffer sb = new StringBuffer("");
		String response_line = "";
		String NL = System.getProperty("line.separator");

		while((response_line=br.readLine())!=null)
		{
			sb.append(response_line+NL);
		}
		br.close();

		response_line=sb.toString();
		Log.e(tag,response_line);

		//parse JSON string
		JSONObject main_obj=new JSONObject(response_line);
		JSONArray projectsJSON =main_obj.getJSONArray("Results");
		for(int i=0;i<projectsJSON.length();i++) {
			//check expiry date of project
			String expiryJSON = projectsJSON.getJSONObject(i).getString("ExpiryDate");
			String expiryString = expiryJSON.substring(6,expiryJSON.indexOf("+"));
			Log.e(tag,expiryString);
			String createdJSON = projectsJSON.getJSONObject(i).getString("CreatedDate");
			String createdString = createdJSON.substring(6,expiryJSON.indexOf("+"));
			//get the expiry date of the project
			Calendar projectExpiry = Calendar.getInstance(Locale.getDefault());
			projectExpiry.setTimeInMillis(Long.parseLong(expiryString));
			Calendar currentTime = Calendar.getInstance(Locale.getDefault());
			if (currentTime.before(projectExpiry)) {
				Project project = new Project(projectsJSON.getJSONObject(i).getString("ID"),createdString,expiryString);
				projects.add(project);
				Log.e(tag,project.getOpenDate() + " " + project.getExpiryDate());
			}
		}

		setProjectDetails(token, projects);

		return projects;
	}

	//set all details of projects
	public static void setProjectDetails(String token, List<Project> projects) throws Exception {

		for (Project project : projects) {

			String url = "https://ivle.nus.edu.sg/api/Lapi.svc/Community?APIKey=" + APIKey + "&AuthToken=" + token + "&ComID=" + project.getID() + "&Duration=0";
			HttpClient client=new  DefaultHttpClient();
			HttpGet get=new HttpGet(url);
			HttpResponse resp=client.execute(get);

			BufferedReader br=new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
			StringBuffer sb = new StringBuffer("");
			String response_line = "";
			String NL = System.getProperty("line.separator");

			while((response_line=br.readLine())!=null)
			{
				sb.append(response_line+NL);
			}
			br.close();

			response_line=sb.toString();
			Log.e(tag,response_line);

			JSONObject main_obj=new JSONObject(response_line);
			JSONObject projectJSON =main_obj.getJSONArray("Results").getJSONObject(0);
			project.setTitle(projectJSON.getString("Title"));
			project.setDescription(projectJSON.getString("Description"));
			project.setCategory(projectJSON.getString("Category"));
			project.setManager(projectJSON.getBoolean("IsManager"));

		}
		//setProjectMembers(token, projects);

	}

	//fill list of members of projects
	public static void setProjectMembers(String token, Project project, String id) throws Exception {

		String url = "https://ivle.nus.edu.sg/api/Lapi.svc/CommunityMembers?APIKey="+APIKey+"&AuthToken="+token+"&ComID="+project.getID();
		HttpClient client=new  DefaultHttpClient();
		HttpGet get=new HttpGet(url);
		HttpResponse resp=client.execute(get);

		BufferedReader br=new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
		StringBuffer sb = new StringBuffer("");
		String response_line = "";
		String NL = System.getProperty("line.separator");

		while((response_line=br.readLine())!=null)
		{
			sb.append(response_line+NL);
		}
		br.close();

		response_line=sb.toString();
		Log.e(tag,response_line);

		JSONObject main_obj=new JSONObject(response_line);
		JSONArray projectsJSON =main_obj.getJSONArray("Results");
		for(int i=0;i<projectsJSON.length();i++) {
			String permission = projectsJSON.getJSONObject(i).getString("Permission");
			if (permission.equals("R")) {
				project.setManager(false);
				if (projectsJSON.getJSONObject(i).getString("UserID").equals(id))
					project.getMembers().add(new Student(projectsJSON.getJSONObject(i).getString("ID"),
							projectsJSON.getJSONObject(i).getString("UserID"),
							projectsJSON.getJSONObject(i).getString("Name"),
							projectsJSON.getJSONObject(i).getString("Email"),false,true,false));
				else
					project.getMembers().add(new Student(projectsJSON.getJSONObject(i).getString("ID"),
							projectsJSON.getJSONObject(i).getString("UserID"),
							projectsJSON.getJSONObject(i).getString("Name"),
							projectsJSON.getJSONObject(i).getString("Email"),false,false,false));

			}
			else {
				project.setManager(true);
				if (permission.equals("O")) {
					if (projectsJSON.getJSONObject(i).getString("UserID").equals(id))
						project.getManagers().add(new Student(projectsJSON.getJSONObject(i).getString("ID"),
								projectsJSON.getJSONObject(i).getString("UserID"),
								projectsJSON.getJSONObject(i).getString("Name"),
								projectsJSON.getJSONObject(i).getString("Email"),true,true,true));
					else 
						project.getManagers().add(new Student(projectsJSON.getJSONObject(i).getString("ID"),
								projectsJSON.getJSONObject(i).getString("UserID"),
								projectsJSON.getJSONObject(i).getString("Name"),
								projectsJSON.getJSONObject(i).getString("Email"),true,false,true));
				}
				else {
					if (projectsJSON.getJSONObject(i).getString("UserID").equals(id))
						project.getManagers().add(new Student(projectsJSON.getJSONObject(i).getString("ID"),
								projectsJSON.getJSONObject(i).getString("UserID"),
								projectsJSON.getJSONObject(i).getString("Name"),
								projectsJSON.getJSONObject(i).getString("Email"),true,true,false));
					else 
						project.getManagers().add(new Student(projectsJSON.getJSONObject(i).getString("ID"),
								projectsJSON.getJSONObject(i).getString("UserID"),
								projectsJSON.getJSONObject(i).getString("Name"),
								projectsJSON.getJSONObject(i).getString("Email"),true,false,false));
				}
			}

		}
		project.setNoManagers(project.getManagers().size());
		project.setNoMembers(project.getMembers().size());

	}

	//add member
	public static String addMemberToProject(String token, String projectID, String memberID, String memberType) throws Exception{

		StringBuffer stringBuffer = new StringBuffer("");
		BufferedReader bufferedReader = null;
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost request = new HttpPost("https://ivle.nus.edu.sg/api/Lapi.svc/Community_AddMember_JSON");
		List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("APIKey", APIKey));
		postParameters.add(new BasicNameValuePair("AuthToken", token));
		postParameters.add(new BasicNameValuePair("ComID", projectID));
		postParameters.add(new BasicNameValuePair("MemberID", memberID));
		postParameters.add(new BasicNameValuePair("MemberType", memberType));


		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParameters);
		request.setEntity(entity);

		HttpResponse response= httpClient.execute(request);

		bufferedReader = new BufferedReader(
				new InputStreamReader(response.getEntity().getContent()));

		String line = "";
		String LineSeparator = System.getProperty("line.separator");
		while ((line = bufferedReader.readLine()) != null) {
			stringBuffer.append(line + LineSeparator);	
		}
		bufferedReader.close();			

		Log.e("tag",stringBuffer.toString());
		return stringBuffer.toString().substring(0, stringBuffer.toString().length()-1);

	}


	public static String updateMember(String token, String projectID, String memberID, String memberType) throws Exception{

		StringBuffer stringBuffer = new StringBuffer("");
		BufferedReader bufferedReader = null;
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost request = new HttpPost("https://ivle.nus.edu.sg/api/Lapi.svc/Community_UpdateMember_JSON");
		List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("APIKey", APIKey));
		postParameters.add(new BasicNameValuePair("AuthToken", token));
		postParameters.add(new BasicNameValuePair("ComID", projectID));
		postParameters.add(new BasicNameValuePair("MemberID", memberID));
		postParameters.add(new BasicNameValuePair("MemberType", memberType));


		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParameters);
		request.setEntity(entity);

		HttpResponse response= httpClient.execute(request);

		bufferedReader = new BufferedReader(
				new InputStreamReader(response.getEntity().getContent()));

		String line = "";
		String LineSeparator = System.getProperty("line.separator");
		while ((line = bufferedReader.readLine()) != null) {
			stringBuffer.append(line + LineSeparator);	
		}
		bufferedReader.close();			

		Log.e("tag",stringBuffer.toString());
		return stringBuffer.toString().substring(0, stringBuffer.toString().length()-1);

	}

	public static String removeMember(String token, String projectID, String memberID) throws Exception{

		StringBuffer stringBuffer = new StringBuffer("");
		BufferedReader bufferedReader = null;
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost request = new HttpPost("https://ivle.nus.edu.sg/api/Lapi.svc/Community_DeleteMember_JSON");
		List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("APIKey", APIKey));
		postParameters.add(new BasicNameValuePair("AuthToken", token));
		postParameters.add(new BasicNameValuePair("ComID", projectID));
		postParameters.add(new BasicNameValuePair("MemberID", memberID));


		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParameters);
		request.setEntity(entity);

		HttpResponse response= httpClient.execute(request);

		bufferedReader = new BufferedReader(
				new InputStreamReader(response.getEntity().getContent()));

		String line = "";
		String LineSeparator = System.getProperty("line.separator");
		while ((line = bufferedReader.readLine()) != null) {
			stringBuffer.append(line + LineSeparator);	
		}
		bufferedReader.close();			

		Log.e("tag",stringBuffer.toString());
		return stringBuffer.toString().substring(0, stringBuffer.toString().length()-1);

	}

	//get all communities category
	public static List<Category> getCategory(String token) throws Exception {
		List<Category> category_list = new ArrayList<Category>();
		String url = "https://ivle.nus.edu.sg/api/Lapi.svc/CommunityCategories?APIKey="+APIKey+"&AuthToken="+token+"&ActiveOnly=true";
		HttpClient client=new  DefaultHttpClient();
		HttpGet get=new HttpGet(url);
		HttpResponse resp=client.execute(get);

		BufferedReader br=new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
		StringBuffer sb = new StringBuffer("");
		String response_line = "";
		String NL = System.getProperty("line.separator");

		while((response_line=br.readLine())!=null)
		{
			sb.append(response_line+NL);
		}
		br.close();

		response_line=sb.toString();
		Log.e(tag,response_line);


		JSONObject main_obj=new JSONObject(response_line);
		JSONArray projectsJSON =main_obj.getJSONArray("Results");
		for(int i=0;i<projectsJSON.length();i++) {
			category_list.add(new Category(projectsJSON.getJSONObject(i).getString("ID"),
					projectsJSON.getJSONObject(i).getString("Title")));
		}

		return category_list;
	}

	//create project - community
	public static String createProjet(String token, String title, String description, String categoryID) throws Exception{

		StringBuffer stringBuffer = new StringBuffer("");
		BufferedReader bufferedReader = null;
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost request = new HttpPost("https://ivle.nus.edu.sg/API/Lapi.svc/Community_Create_JSON");
		List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("APIKey", APIKey));
		postParameters.add(new BasicNameValuePair("AuthToken", token));
		postParameters.add(new BasicNameValuePair("Title", title));
		postParameters.add(new BasicNameValuePair("Description", description));
		postParameters.add(new BasicNameValuePair("AccessType", "M"));
		postParameters.add(new BasicNameValuePair("DefaultForum", "Y"));
		postParameters.add(new BasicNameValuePair("DefaultWorkbin", "Y"));
		postParameters.add(new BasicNameValuePair("CategoryID", categoryID));
		postParameters.add(new BasicNameValuePair("Tags", ""));

		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParameters);
		request.setEntity(entity);

		HttpResponse response= httpClient.execute(request);

		bufferedReader = new BufferedReader(
				new InputStreamReader(response.getEntity().getContent()));

		String line = "";
		String LineSeparator = System.getProperty("line.separator");
		while ((line = bufferedReader.readLine()) != null) {
			stringBuffer.append(line + LineSeparator);	
		}
		bufferedReader.close();			

		Log.e("tag",stringBuffer.toString());
		return stringBuffer.toString().substring(0, stringBuffer.toString().length()-1);

	}

	//updaye project - community
	public static String updateProjet(String token, String comID, String title, String description, String categoryID, String openDate, String expiryDate) throws Exception{

		StringBuffer stringBuffer = new StringBuffer("");
		BufferedReader bufferedReader = null;
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost request = new HttpPost("https://ivle.nus.edu.sg/API/Lapi.svc/Community_Update_JSON");
		List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("APIKey", APIKey));
		postParameters.add(new BasicNameValuePair("AuthToken", token));
		postParameters.add(new BasicNameValuePair("ComID", comID));
		postParameters.add(new BasicNameValuePair("Title", title));
		postParameters.add(new BasicNameValuePair("Description", description));
		postParameters.add(new BasicNameValuePair("AccessType", "M"));
		postParameters.add(new BasicNameValuePair("DefaultForum", "Y"));
		postParameters.add(new BasicNameValuePair("DefaultWorkbin", "Y"));
		postParameters.add(new BasicNameValuePair("CategoryID", categoryID));
		postParameters.add(new BasicNameValuePair("Tags", ""));
		postParameters.add(new BasicNameValuePair("DisplayMembersTo", "M"));
		postParameters.add(new BasicNameValuePair("OpeningDate", openDate));
		postParameters.add(new BasicNameValuePair("ExpiryDate", expiryDate));

		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParameters);
		request.setEntity(entity);

		HttpResponse response= httpClient.execute(request);

		bufferedReader = new BufferedReader(
				new InputStreamReader(response.getEntity().getContent()));

		String line = "";
		String LineSeparator = System.getProperty("line.separator");
		while ((line = bufferedReader.readLine()) != null) {
			stringBuffer.append(line + LineSeparator);	
		}
		bufferedReader.close();			

		Log.e("tag",stringBuffer.toString());
		return stringBuffer.toString().substring(0, stringBuffer.toString().length()-1);

	}

}
